﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChoViet.Lib.Common;
using System.Linq.Dynamic;
using ChoViet.Lib.Helpers;
using ChoViet.Model;
using ChoViet.CMS.ViewModels;

namespace ChoViet.CMS.Controllers
{
    [RoleHelper(Roles = RoleSystem.Dictionary)]
    public class AdAttributeController : Controller
    {
        /// <summary>
        /// Created by: VietLV
        /// Created date: 01/05/2012
        /// Description: Manage AdAttribute controller
        /// </summary>
        /// <returns></returns>

        #region GET: /AdAttribute/IndexCms
        public ActionResult IndexCms(AdAttributeIndexViewModel c)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (UserManager.CheckRole(RoleSystem.AdAttribute))
                {
                    c.CurrentCat = Request["CurrentCat"] != null && Request["CurrentCat"].Trim().Length > 0 ? Convert.ToInt32(Request["CurrentCat"]) : 0;
                    UpdateModel(c);
                    string order = UserState.getUserStateFromRequest("category.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("category.orderDir", "orderDir", "desc").ToString();
                    c.AdAttributes = eDataContext.AdAttributes
                                        //.Where(e =>c!= null && c.Keyword != null && c.Keyword.Trim().Length > 0 ? e.Name.ToLower().Contains(c.Keyword.Trim().ToLower()) : true)
                                        .Where(e =>c.CurrentCat != null && c.CurrentCat >0 ? e.CateID == c.CurrentCat : false)
                                        .OrderBy(string.Format("{0} {1}", order, orderDir)).ToList();   
                    c.CategoryBuiltTree = Model.CategoryManager.BuiltCombobox(c.CurrentCat);
                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(c);
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                eDataContext.Dispose();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /AdAttribute/CreateCms
        public ActionResult CreateCms()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                AdAttributeEditViewModel param = new AdAttributeEditViewModel();
                param.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
                param.ParrentCatrgories = eDataContext.Categories.Where(e => e.ParentID == null).ToList();
                return View(param);
            }
            catch (Exception exp)
            {
                eDataContext.Dispose();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /AdAttribute/CreateCms
        [HttpPost]
        public ActionResult CreateCms(AdAttributeEditViewModel c)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();

                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                UpdateModel(c);
                c.AdAttribute.CreatedBy = UserManager.GetUserId();
                c.AdAttribute.CreatedDate = DateTime.Now;
                c.AdAttribute.CateID = Convert.ToInt32(Request["CategoryId"]);

                eDataContext.AdAttributes.InsertOnSubmit(c.AdAttribute);
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("IndexCms");
            }
            catch
            {
                eDataContext.Transaction.Rollback();
                eDataContext.Dispose();
                return View();
            }
        }
        #endregion

        #region GET: /AdAttribute/DetailsCms
        public ActionResult DetailsCms(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                var param =new AdAttributeDetailsViewModel();
                param.AdAttribute = eDataContext.AdAttributes.FirstOrDefault(e => e.ID == id);
                param.AdAttributeValues = eDataContext.AdAttributeValues.Where(e => e.AttributeID == id).ToList();
                param.CateName = eDataContext.Categories.Where(e => e.ID == param.AdAttribute.CateID).Select(e => e.Name).FirstOrDefault();
                return View(param);
            }
            catch
            {
                eDataContext.Dispose();
                return View();
            }
        }
        #endregion

        #region GET: /AdAttribute/EditCms/5
        public ActionResult EditCms(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                var param = new AdAttributeEditViewModel();
                param.AdAttribute = eDataContext.AdAttributes.Where(e => e.ID == id).SingleOrDefault();
                param.ParrentCatrgories = eDataContext.Categories.Where(e => e.ParentID == null || e.ParentID ==0).ToList();
                param.CategoryBuiltTree = CategoryManager.BuiltCombobox(param.AdAttribute.CateID.Value);
                return View(param);
            }
            catch (Exception exp)
            {
                eDataContext.Dispose();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /AdAttribute/EditCms/5
        [HttpPost]
        public ActionResult EditCms(int id, AdAttributeEditViewModel c)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                c.AdAttribute = eDataContext.AdAttributes.Where(e => e.ID == id).SingleOrDefault();
                UpdateModel(c);
                c.AdAttribute.CateID = Convert.ToInt32(Request["CategoryId"]);
                c.AdAttribute.ModifyBy = UserManager.GetUserId();
                c.AdAttribute.ModifyDate = DateTime.Now;
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("IndexCms");
            }
            catch(Exception exp)
            {
                eDataContext.Transaction.Rollback();
                eDataContext.Dispose();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /AdAttribute/DeleteCms/5
        public ActionResult DeleteCms(int id)
       {
           ChoVietDataContext eDataContext = new ChoVietDataContext();
           try
           {
               if (UserManager.CheckRole(RoleSystem.Dictionary))
               {
                   var item = eDataContext.AdAttributes.FirstOrDefault(e => e.ID == id);
                   return View(item);
               }
               else
               {
                   ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                   return View();
               }
           }
           catch (Exception exp)
           {
               ViewData[Messages.MessageInfo] = exp.Message;
               return View();
           }
       }
        #endregion

        #region POST: /AdAttribute/DeleteCms/5
        [HttpPost]
        public ActionResult DeleteCms(int id, FormCollection collection)
       {
           ChoVietDataContext eDataContext = new ChoVietDataContext();
           try
           {
               if (UserManager.CheckRole(RoleSystem.Dictionary))
               {
                   if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                   eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                   eDataContext.AdAttributeMaps.DeleteAllOnSubmit(eDataContext.AdAttributeMaps.Where(e => e.AttributeID== id).ToList());
                   eDataContext.AdAttributeValues.DeleteAllOnSubmit(eDataContext.AdAttributeValues.Where(e => e.AttributeID == id).ToList());
                   var item = eDataContext.AdAttributes.FirstOrDefault(e => e.ID == id);
                   if (item != null)
                   {
                       eDataContext.AdAttributes.DeleteOnSubmit(item);
                   }
                   eDataContext.SubmitChanges();
                   eDataContext.Transaction.Commit();
                   return RedirectToAction("IndexCms");
               }
               else
               {
                   ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                   return View();
               }
           }
           catch (Exception exp)
           {
               eDataContext.Transaction.Rollback();
               eDataContext.Dispose();
               ViewData[Messages.MessageInfo] = exp.Message;
               return View();
           }
       }
       #endregion


        #region POST: /AdAttribute/AddAdValue/5
        [HttpPost]
        public JsonResult AddAdValue(int id)
       {
           ChoVietDataContext eDataContext = new ChoVietDataContext();
           try
           {
               var value = Request["advalue"];
               AdAttributeValue item = new AdAttributeValue() {AttributeID=id,Value=value };
               eDataContext.AdAttributeValues.InsertOnSubmit(item);
               eDataContext.SubmitChanges();
               return Json(true);
           }
           catch
           {
               eDataContext.Dispose();
               return Json(false);
           }
       }
       #endregion
    }
}
